import Taro from "@tarojs/taro"
import { postLoginbycodeCode } from "@/apis/endpoint/home"
import { useAuthStore } from "@/store"
import { getStorageToken, removeStorageToken } from '@/utils/ls/token'
import { removeStorageUserInfo } from '@/utils/ls/userInfo'

/** 是否正在发起登录 */
let isAuthing = false
export const getIsAuthing = () => isAuthing
export const setIsAuthing = (state: boolean) => (isAuthing = state)

const wechatLoginPath = "/loginbycode"

export const wxLogin = function (afterAuth?: (fulfilled: boolean) => any) {
  Taro.login({
    success(res) {
      if (res.code) {
        postLoginbycodeCode(res.code)
          .send()
          .then((userInfo) => {
            if (userInfo) {
              const store = useAuthStore.getState()
              store.setUserInfo(userInfo)
              afterAuth && afterAuth(true)
            } else {
              Taro.showToast({
                title: "登录失败",
                icon: "none",
                mask: false
              })
              afterAuth && afterAuth(false)
            }
          })
          .catch(() => {
            afterAuth && afterAuth(false)
          })
      } else {
        Taro.showToast({
          title: "登录失败！" + res.errMsg,
          icon: "none",
          mask: false
        })
        afterAuth && afterAuth(false)
      }
    }
  })
}

export const isLoginRequest = (reqUrl: string) => {
  return reqUrl.indexOf(wechatLoginPath) !== -1
}
export function removeAuthInfo() {
  removeStorageToken()
  removeStorageUserInfo()
}
export function isLogin() {
    return Boolean(getStorageToken())
}
